package cn.edu.zut.salarymanagesystem.fragments;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import androidx.fragment.app.Fragment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.edu.zut.salarymanagesystem.R;
import cn.edu.zut.salarymanagesystem.activities.CalendarViewActivity;
import cn.edu.zut.salarymanagesystem.activities.LoginActivity;
import cn.edu.zut.salarymanagesystem.activities.ResetPasswordActivity;
import cn.edu.zut.salarymanagesystem.activities.ShowCanAddItemActivity;
import cn.edu.zut.salarymanagesystem.bean.vo.OperateResult;
import cn.edu.zut.salarymanagesystem.config.Storage;
import cn.edu.zut.salarymanagesystem.utils.AlertBuilder;
import cn.edu.zut.salarymanagesystem.utils.MD5Helper;
import cn.edu.zut.salarymanagesystem.utils.Browser;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class PersonFragment extends Fragment {
    private static final byte NETWORK_ERROR = 0x01;
    private static final byte LOGOUT = 0x02;
    private static final byte GET_AVATAR = 0x03;
    private static final byte TOAST_TIP = 0x04;
    private static final byte CALC_REMOTE_AVATAR_HASH = 0x05;
    private static final byte RESET = 0x06;
    private static final int CANCEL_COMIN = 0x07;
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case NETWORK_ERROR:
                    Toast.makeText(getActivity(), "请求失败！请检查网络设置", Toast.LENGTH_SHORT).show();
                    break;
                case LOGOUT:
                    Storage.currentUser = null;
                    Browser.flushClient();
                    flushSharedPreferences();
                    Toast.makeText(getActivity(), "注销成功！请重新登录~", Toast.LENGTH_SHORT).show();
                    break;
                case RESET:
                    Toast.makeText(getActivity(), "修改密码成功", Toast.LENGTH_SHORT).show();
                    break;
                case GET_AVATAR:
                    byte[] bytes = (byte[]) msg.obj;
                    Bitmap originalBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    if (originalBitmap != null) {
                        Bitmap mutableBitmap = originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
                        Bitmap resizedBitmap = Bitmap.createScaledBitmap(mutableBitmap, 800, 800, true);
                        originalBitmap.recycle();
                        File resizedFile = new File(getActivity().getFilesDir(), Storage.currentUser.getAvatar());
                        try {
                            FileOutputStream fos = new FileOutputStream(resizedFile);
                            resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); // 保存为 PNG 格式，可以根据需求修改
                            fos.close();
                        } catch (IOException e) {
                            Log.e("d8g", "调整大小后保存头像失败！");
                            e.printStackTrace();
                        }
                        resizedBitmap.recycle();
                        imgAvatar.setImageBitmap(BitmapFactory.decodeFile(resizedFile.getAbsolutePath()));
                        PersonFragment.this.remoteAvatarHash = MD5Helper.calc(bytes);
                    }
                    break;
                case TOAST_TIP:
                    Toast.makeText(getActivity(), (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case CALC_REMOTE_AVATAR_HASH:
                    PersonFragment.this.remoteAvatarHash = (String) msg.obj;
                    break;
                case CANCEL_COMIN:
                    OperateResult operateResult = (OperateResult) msg.obj;
                    Log.i("d8g", "handleMessage: " + operateResult.toString());
                    switch (operateResult.getCode()) {
                        case 200://取消成功返回1
                            Toast.makeText(getActivity(), "取消签到成功", Toast.LENGTH_SHORT).show();
                            break;
                        case 500://取消失败返回0
                            Toast.makeText(getActivity(), "取消签到失败!服务器错误！", Toast.LENGTH_SHORT).show();
                            break;
                        case 400://今日还没签到
                            Toast.makeText(getActivity(), "您今日还未签到", Toast.LENGTH_SHORT).show();
                            break;
                        default:
                            Toast.makeText(getActivity(), "取消签到失败，请排查原因", Toast.LENGTH_SHORT).show();
                    }
            }
        }
    };
    private Activity activity;

    public PersonFragment() {
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (Activity) context;
        this.localAvatarPath = getActivity().getFilesDir() + "/" + Storage.currentUser.getAvatar();
    }

    private String localAvatarPath = null;// 本地头像文件路径
    private final String remoteAvatarUrl = Storage.url + "/avatar/getMy";
    private String remoteAvatarHash; // 远程头像图片的哈希值
    private ImageView imgAvatar; // 用于显示头像的ImageView

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_person, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        ((TextView) view.findViewById(R.id.wk_name)).setText(Storage.currentUser.getUserName());
        ((TextView) view.findViewById(R.id.wk_id)).setText(String.valueOf(Storage.currentUser.getUid()));
        ((TextView) view.findViewById(R.id.wk_gp)).setText(Storage.currentUser.getGroupName());
        Button btnLogout = view.findViewById(R.id.btn_logout);
        Button peReset = view.findViewById(R.id.pe_reset);
        Button cancelAttendence = view.findViewById(R.id.cancel_attendence);
        Button btnShowItems = view.findViewById(R.id.btn_show_items);
        Button btnShowAttendance = view.findViewById(R.id.btn_show_attendance);
        this.imgAvatar = view.findViewById(R.id.avatar);
        btnLogout.setOnClickListener(this.btnLogoutListener);
        peReset.setOnClickListener(this.peResetListener);
        btnShowAttendance.setOnClickListener(v -> startActivity(new Intent(getContext(), CalendarViewActivity.class)));
        cancelAttendence.setOnClickListener(this.cancelAttendenceListener);
        btnShowItems.setOnClickListener(this.peShowListenter);
        //渲染头像： case 无本地头像，请求；case 有本地头像，但是哈希值不同（已更新）；case 有本地头像，哈希相等，使用本地
        //TODO: 这里可以进行头像缓存机制，但由于时间限制先进性简单处理
        if (!new File(localAvatarPath).exists()) {
            requestAvatar();
        } else {
            //获取本地头像文件
            Bitmap bitmap = BitmapFactory.decodeFile(localAvatarPath);
            //通过调用系统API，利用RoundedBitmapDrawable实现圆角功能
            RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap);
            roundedBitmapDrawable.setCornerRadius(400); //设置圆角
            roundedBitmapDrawable.setAntiAlias(true); //设置抗锯齿
            imgAvatar.setImageDrawable(roundedBitmapDrawable);
        }
        view.findViewById(R.id.btn_show_items).setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), ShowCanAddItemActivity.class);
            startActivity(intent);
        });
    }

    private void requestAvatar() {
        OkHttpClient client = Browser.getClient();
        Request request = new Request.Builder().url(remoteAvatarUrl).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Message message = Message.obtain();
                message.what = NETWORK_ERROR;
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Message message = Message.obtain();
                message.what = GET_AVATAR;
                message.obj = response.body().bytes();
                handler.sendMessage(message);
            }
        });
    }

    private void flushSharedPreferences() {
        SharedPreferences.Editor edit = getContext().getSharedPreferences("COOKIE", Context.MODE_PRIVATE).edit();
        edit.clear();
        edit.apply();
    }

    private View.OnClickListener peResetListener = view -> {
        Intent intent = new Intent(getActivity(), ResetPasswordActivity.class);
        startActivity(intent);
    };
    private View.OnClickListener cancelAttendenceListener = view -> {
        AlertBuilder.getCancelDialog(PersonFragment.this, handler).show();
    };
    private View.OnClickListener peShowListenter = view -> {
        Intent intent = new Intent(getActivity(), ShowCanAddItemActivity.class);
        startActivity(intent);
    };
    private View.OnClickListener btnLogoutListener = view -> {
        SharedPreferences preferences = getActivity().getSharedPreferences("COOKIE", Context.MODE_PRIVATE);
        preferences.edit().clear();
        preferences.edit().commit();
        new File(localAvatarPath).delete();
        OkHttpClient client = Browser.getClient();
        Request request = new Request.Builder().url(Storage.url + "/login/logout").build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
                handler.sendEmptyMessage(NETWORK_ERROR);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                handler.sendEmptyMessage(LOGOUT);
                startActivity(intent);
                getActivity().finish();
            }
        });
    };

}